package com.game.base.glideV4.tranform;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
import com.game.base.glideV4.tranform.blur.FastBlur;

import java.security.MessageDigest;

import androidx.annotation.NonNull;

/**
 * 图片高斯模糊处理
 */
public class BlurBitmapTranformation extends BitmapTransformation {
    private static int DEFAULT_DOWN_SAMPLING = 4;
    private int radius;

    public BlurBitmapTranformation(int radius) {
        super();
        this.radius = radius;
    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap transform = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);  // 先得到 CenterCrop处理，然后进行模糊处理
        return blurCrop(pool, transform);
    }

    private Bitmap blurCrop(BitmapPool pool, Bitmap toTransform) {

        if (toTransform == null) {
            return null;
        }
        if (radius <= 0) {
            radius = 25;
        }

        int width = toTransform.getWidth();
        int height = toTransform.getHeight();
        int scaledWidth = width / DEFAULT_DOWN_SAMPLING;
        int scaledHeight = height / DEFAULT_DOWN_SAMPLING;

        Bitmap bitmap = pool.get(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
        if (bitmap == null)
            bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);

        Canvas canvas = new Canvas(bitmap);
        canvas.scale(1 / (float) DEFAULT_DOWN_SAMPLING, 1 / (float) DEFAULT_DOWN_SAMPLING);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(toTransform, 0, 0, paint);

        return FastBlur.blur(bitmap, radius, true);
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
    }
}
